package com.hammer.m3u8downloader.util;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.hammer.m3u8downloader.entity.M3U8DownloadItemEntity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class LocalM3U8Manager {
    private static LocalM3U8Manager instance;
    private static SQLiteDatabase database;
    private static final String CREAT_REQUEST_TABLE = "CREATE TABLE IF NOT EXISTS m3u8 ( id integer PRIMARY KEY,taskName text,taskUrl text,taskFile text,progress integer,status integer,fileSize text)";

    public static LocalM3U8Manager getInstance(Context context) {
        if (instance == null) {
            instance = new LocalM3U8Manager();
        }
        if (database == null) {
            init(context);
        }
        return instance;
    }

    public boolean isExists(String taskUrl) {
        int count = 0;
        if (database != null) {
            Cursor cursor = database.rawQuery("SELECT count(*) FROM m3u8 WHERE taskUrl = '" + taskUrl + "'", null);
            if (cursor.moveToNext()) {
                count = cursor.getInt(0);
            }
            cursor.close();
        }
        return count != 0;
    }

    public int getTaskStatus(String taskUrl) {
        int status = 0;
        Cursor cursor = null;
        try {
            cursor = database.rawQuery("SELECT * FROM m3u8 where taskUrl = '" + taskUrl + "'", null);
            if (cursor.moveToFirst()) {
                do {
                    status = cursor.getInt(5);
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if ((null != cursor) && (!cursor.isClosed())) {
                cursor.close();
            }
        }
        return status;
    }


    public void addTask(String taskName, String taskUrl, String taskFile, int progress, int status) {
        if (database != null) {
            if (!isExists(taskUrl)) { //跳过已禁用的源
                database.execSQL("INSERT INTO m3u8 VALUES (null,'" + taskName + "','" + taskUrl + "','" + taskFile + "'," + progress + "," + status + ",'0 kb')");
            }
        }
    }


    public void updateTaskInfo(String taskUrl, int progress, int status, String fileSize) {
        if (database != null) {
            database.execSQL("update m3u8 set progress = " + progress + ",status = " + status + ",fileSize = '" + fileSize + "' where taskUrl = '" + taskUrl + "'");
        }
    }

    public void deleteTask(String taskUrl) {
        if (database != null) {
            database.execSQL("delete from m3u8 where taskUrl = '" + taskUrl + "'");
        }
    }


    public String getTaskFile(String taskUrl) {
        String file = "";
        Cursor cursor = null;
        try {
            cursor = database.rawQuery("SELECT * FROM m3u8 where taskUrl = '" + taskUrl + "'", null);
            if (cursor.moveToFirst()) {
                do {
                    file = cursor.getString(3);
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if ((null != cursor) && (!cursor.isClosed())) {
                cursor.close();
            }
        }
        return file;
    }


    private static void creatDataBase(Context context) {
        File file = new File(getDataBasePath(context) + "/m3u8.db");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void craetTable() {
        if (database != null) {
            database.execSQL(CREAT_REQUEST_TABLE);
        }
    }

    public static void init(Context context) {
        creatDataBase(context);
        File file = new File(getDataBasePath(context) + "/m3u8.db");
        if (file.exists()) {
            database = context.openOrCreateDatabase(getDataBasePath(context) + "/m3u8.db", 0, null);
        }
        craetTable();
    }


    public List<M3U8DownloadItemEntity> getTaskList(String statusHz) {
        String sql = "SELECT * FROM m3u8 WHERE status " + statusHz;
        List<M3U8DownloadItemEntity> taskInfos = new ArrayList<>();
        Cursor cursor = null;
        try {
            cursor = database.rawQuery(sql, null);
            if (cursor.moveToFirst()) {
                do {
                    M3U8DownloadItemEntity taskInfo = new M3U8DownloadItemEntity();
                    taskInfo.setTaskName(cursor.getString(1));
                    taskInfo.setTaskUrl(cursor.getString(2));
                    taskInfo.setTaskFile(cursor.getString(3));
                    taskInfo.setProgress(cursor.getInt(4));
                    taskInfo.setStatus(cursor.getInt(5));
                    taskInfo.setFileSize(cursor.getString(6));
                    taskInfos.add(taskInfo);
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if ((null != cursor) && (!cursor.isClosed())) {
                cursor.close();
            }
        }
        return taskInfos;
    }

    private static String getDataBasePath(Context context) {
        String dataBasePath;
        File dir = context.getExternalFilesDir("");
        if (dir != null) {
            dataBasePath = dir.getAbsolutePath() + "/database";
        } else {
            dataBasePath = context.getFilesDir().getAbsolutePath() + "/database";
        }
        if (!new File(dataBasePath).exists()) {
            new File(dataBasePath).mkdirs();
        }
        return dataBasePath;
    }
}
